package com.houger.facade;


import cn.hutool.extra.servlet.ServletUtil;
import com.houger.UidGenerator;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * @author Houger.
 * @date 2023年11月13日 10:34.
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/uid")
public class UidFacade {
    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Resource
    UidGenerator cachedUidGenerator;

    @GetMapping("/get")
    public Long getUid(){
        redisTemplate.opsForValue().set("kk1","vv1",600, TimeUnit.SECONDS);
        redisTemplate.opsForHash().put("hk1","name","张三丰");
        return cachedUidGenerator.getUID();
    }

    @GetMapping("/parse/{uid}")
    public String parseUid(@PathVariable("uid") Long uid, HttpServletRequest request){
        System.out.println("IP : " + getIpAddr(request));
        return cachedUidGenerator.parseUID(uid);
    }
    public String getIpAddr(HttpServletRequest request) {
        final Enumeration<String> headerNames = request.getHeaderNames();
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("x-forwarded-for ip: " + ip);

        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            // System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            // System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            // System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            // System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            // System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            // System.out.println("getRemoteAddr ip: " + ip);
        }

        // System.out.println("获取客户端ip: " + ip);
        return ip;
    }
}
